package com.djl.sqtg.controller;

import com.alibaba.fastjson.JSONObject;
import com.djl.sqtg.entity.*;
import com.djl.sqtg.entity.Collection;
import com.djl.sqtg.service.IUserService;
import com.djl.sqtg.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("users")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    //微信用户一键登录
    @GetMapping("login/{code}")
    public JsonResult user_login(@PathVariable("code") String code){
        Map<String, String> param = new HashMap<>();
        param.put("appid", WeChatConfig.WX_LOGIN_APPID);
        param.put("secret", WeChatConfig.WX_LOGIN_SECRET);
        param.put("js_code", code);
        param.put("grant_type", WeChatConfig.WX_LOGIN_GRANT_TYPE);
        // 发送请求获取openid
        String wxResult = HttpClientUtil.doGet(WeChatConfig.WX_LOGIN_URL, param);
        JSONObject json = JSONObject.parseObject(wxResult);
        String openid = json.get("openid").toString();
        User data = userService.findOpenid(openid);
        /*
        * 如果查询为空则该用户在数据库中无数据，故需要注册
        * 否则就是登陆成功并返回用户数据
        * */
        if (data==null){
            User user = new User();
            user.setOpenid(openid);
            String msg="用户未注册，请注册";
            return new JsonResult(NO,msg,user);
        } else {
            return new JsonResult<User>(OK,data);
        }
    }


    @PostMapping("register")
    public JsonResult<User> login(@RequestBody User user) {
        System.out.println(user);
        String  username =user.getUsername();
        String  avatar =user.getAvatar();
        String  openid =user.getOpenid();
        System.out.println("登录用户名："+username+",头像url："+avatar+",   openid："+openid);
        userService.register(username,avatar,openid,DateUtil.getNowTime());
        User data = userService.findOpenid(openid);
        return new JsonResult<User>(OK,data);
    }

    /*计算用户地址与团长地址距离*/
    @GetMapping("distance/{longitude}/{latitude}")
    public JsonResult distance(@PathVariable double longitude,@PathVariable double latitude) {
        List<Colonel> colonel = userService.getColonelAddress();
        List data = new ArrayList<>();
        for (int i=0;i<colonel.size();i++){
            JSONObject item = new JSONObject();
            item.put("longitude",colonel.get(i).getLongitude());
            item.put("latitude",colonel.get(i).getLatitude());
            item.put("colonelname",colonel.get(i).getColonelname());
            item.put("community",colonel.get(i).getCommunity());
            item.put("cid",colonel.get(i).getCid());
            item.put("address",colonel.get(i).getAddress());
            String distance = DistanceUtil.getDistance(longitude,latitude,colonel.get(i).getLongitude(),colonel.get(i).getLatitude());
            item.put("distance",distance);
            String distanceStr = distance.substring(0,distance.length()-2);
            double distanceNum = Double.parseDouble(distanceStr);
            if (distanceNum<10) {
                data.add(item);
            }
        }
        return new JsonResult(OK,data);
    }

//删除一个用户
    @GetMapping({"{uid}/delUserByUid"})
    public JsonResult delUserByUid(@PathVariable("uid") Integer uid){
        System.out.println("删除用户："+uid);
//        userService.delUserByUid(uid);
        return new JsonResult(OK);
    }

//批量删除多个用户
    @GetMapping({"{uids}/delManyUsers"})
    public JsonResult delManyUsers(@PathVariable("uids") Integer[] uids){
        System.out.println("批量删除用户：");
        System.out.println("批量删除商品：");
        for (int i=0;i<uids.length;i++){
            System.out.println(uids[i]);
        }
//        userService.delManyUsers(uids);
        return new JsonResult(OK);
    }

    @PostMapping("findByUsername")
    public JsonResult<List<User>> findByUsername(@RequestParam("username") String username) {
        List<User> data = userService.findByUsername(username);
        System.out.println("根据用户名查询的结果："+data);
        System.out.println("根据用户名查询的结果："+data.size());
        if (data.size()==0){
            System.out.println("查询失败");
            return new JsonResult<List<User>>(NO,data);
        }
        System.out.println("查询成功");
        return new JsonResult<List<User>>(OK,data);
    }

//    分页获取用户数据
    @RequestMapping("getUserByPageNum")
    public LayuiResultData getUserByPageNum(
                                            @RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "10") Integer pageSize,
                                            String dateRange,
                                            String username,
                                            String telep,
                                            String memberstate
    ) {
        System.out.println("进入页面函数————————当前页码"+pageNum+"—————————————当前每页数量"+pageSize+"---------");
        System.out.println("dateRange："+dateRange);
        System.out.println("username："+username);
        System.out.println("telep："+telep);
        System.out.println("memberstate："+memberstate);
        List<User> data;
        Integer count;
        if ((dateRange==null && username==null && telep==null && memberstate==null) || (dateRange=="" && username=="" && telep=="" && memberstate=="")){
            System.out.println("总数据......");
            data = userService.getUserByPageNum((pageNum-1)*10,pageSize);
            count = userService.getAllUsers();
        }else{
            System.out.println("search..........");
            String startDate=null;
            String endDate=null;
            Integer memberstate0;
            if (memberstate==""){
                 memberstate0=null;
            }else {
                memberstate0=Integer.valueOf(memberstate);
            }
            System.out.println(memberstate0);
            if (dateRange.isEmpty()){
                System.out.println("dateRange为空");
                data = userService.getUserBySearch(startDate,endDate,username,telep,memberstate0,(pageNum-1)*10,pageSize);
                count = userService.getUserBySearchCount(startDate,endDate,username,telep, memberstate0);
            }else{
                String[]  dateArry  = dateRange.split(" ~ ");
                data = userService.getUserBySearch(dateArry[0],dateArry[1],username,telep,memberstate0,(pageNum-1)*10,pageSize);
                count = userService.getUserBySearchCount(dateArry[0],dateArry[1],username,telep, memberstate0);
            }

        }
        System.out.println("分页查询结果："+data);
        System.out.println("查询数据数量"+count);
        LayuiResultData layuiResultData=new LayuiResultData();
        layuiResultData.setData(data);
        layuiResultData.setCount(count);
        layuiResultData.setPageNum(pageNum);
        layuiResultData.setPageSize(pageSize);
        return  layuiResultData;
    }

    @RequestMapping("getGroupByTzid/{tzid}")
    public LayuiResultData getUserByPageNum(@PathVariable Integer tzid,User user,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        System.out.println("进入页面函数————————当前页码"+pageNum+"—————————————当前每页数量"+pageSize+"---------"+user);
        String username=user.getUsername();
        String telep=user.getTelep();
        System.out.println(username+"-----"+telep);
        List<User> data;
        Integer count;
        if (username==null|| (username=="" && telep=="")){
            System.out.println("总数据......");
            data = userService.getGroupByTzid((pageNum-1)*10,pageSize,tzid);
            count = userService.getAllUsersByTzid(tzid);
        }else{
            System.out.println("search..........");
            data = userService.getUserBySearchTzid(username,telep,(pageNum-1)*10,pageSize,tzid);
            count = userService.getUserBySearchCountTzid(username,telep,tzid);
        }
        System.out.println("分页查询结果："+data);
        System.out.println("查询数据数量"+count);
        LayuiResultData layuiResultData=new LayuiResultData();
        layuiResultData.setData(data);
        layuiResultData.setCount(count);
        layuiResultData.setPageNum(pageNum);
        layuiResultData.setPageSize(pageSize);
        return  layuiResultData;
    }

    @GetMapping({"getAllUser"})
    public LayuiResultData getAllUser() {
        List<User> data = userService.getAllUser();
        LayuiResultData layuiResultData = new LayuiResultData();
        layuiResultData.setData(data);
        layuiResultData.setCount(userService.getAllUsers());
        return layuiResultData;
    }

    @GetMapping({"chooeseColonel/{uid}/{cid}"})
    public JsonResult chooeseColonel(@PathVariable Integer uid,@PathVariable Integer cid) {
        userService.chooeseColonel(uid,cid);
        return new JsonResult<>(OK);
    }
//足迹
    @GetMapping({"getFootprintByUid/{uid}"})
    public JsonResult getFootprintByUid(@PathVariable Integer uid) {
        List<Goods> data = userService.getFootprintByUid(uid);
        return new JsonResult<>(OK,data);
    }
    //收藏
    @GetMapping({"addCollection/{uid}/{gid}"})
    public JsonResult addCollection(@PathVariable Integer uid,@PathVariable Integer gid) {
        Collection collection = userService.getCollection(uid,gid);
        if (collection!=null){//此次点击，该商品已收藏，故前端要点击后显示为未收藏  取消收藏
            userService.delCollectionByUidGid(uid,gid); //取消收藏，删除该收藏
            return new JsonResult(OK,0);
        }
        userService.collection(uid,gid,DateUtil.getNowTime()); //添加收藏
        return new JsonResult(OK,1);
    }

    @GetMapping({"getCollection/{uid}/{gid}"})
    public JsonResult getCollection(@PathVariable Integer uid,@PathVariable Integer gid) {
        System.out.println(uid+"---------"+gid);
        Collection data = userService.getCollection(uid,gid);
        System.out.println(data);
        Integer collectionstate=0;
        if (data!=null){//已收藏
            collectionstate=1;
            System.out.println(collectionstate);
            return new JsonResult(OK,collectionstate);
        }
        System.out.println(collectionstate);
        return new JsonResult(OK,collectionstate);
    }

    @GetMapping({"getAllCollection/{uid}"})
    public JsonResult getAllCollection(@PathVariable Integer uid) {
        List<Collection> data = userService.getAllCollection(uid);
        return new JsonResult(OK,data);
    }

    @GetMapping({"delCollection/{cid}"})
    public JsonResult delCollection(@PathVariable Integer cid) {
        Integer data = userService.delCollection(cid);
        return new JsonResult(OK);
    }
    //用户获取优惠券
    @GetMapping({"getCoupon"})
    public JsonResult getCoupon() {
        List<Coupon> data = userService.getCoupon();
        return new JsonResult(OK,data);
    }
    //删除团长下属团员
    @GetMapping({"updateTzidNull/{uid}"})
    public JsonResult updateTzidNull(@PathVariable Integer uid) {
        userService.updateTzidNull(uid);
        return new JsonResult(OK);
    }
}
